package com.cloudm.technician.ui.modules.cloudm_box.machine

import com.cloudm.technician.data.model.MachineInfo
import com.cloudm.technician.data.network.CloudmBoxApi
import com.cloudm.technician.ui.base.RxPresenter

/**
 * 作者: wesley
 * 时间: 2017/12/20
 * 描述: 业务逻辑
 */
class MachinePresenter(private val view: MachineContract.View,
                       private val cloudmBoxApi: CloudmBoxApi) : RxPresenter(),
        MachineContract.Presenter {

    override fun buildTitleByFlag(flag: Int) {
        when (flag) {
            0 -> view.onMachineTypeTitleReceive()
            1 -> view.onMachineBrandTitleReceive()
            2 -> view.onMachineModelTitleReceive()
        }
    }

    override fun loadData(flag: Int, typeId: Int, brandId: Int, modelId: Int) {
        when (flag) {
            0 -> loadMachineTypeInfo(typeId)
            1 -> loadMachineBrandInfo(brandId)
            2 -> loadMachineModelInfo(typeId, brandId, modelId)
        }
    }


    override fun loadMachineTypeInfo(typeId: Int) {
        request(cloudmBoxApi.getMachineTypeInfo(), view, onSuccess = { info, loadMore ->
            val position = getPosition(typeId, info)
            view.loadSuccess(info, loadMore)
            view.scrollToPosition(position)
        }, onFailure = { errorMsg ->
            view.loadFailure(errorMsg)
        })
    }

    override fun loadMachineBrandInfo(brandId: Int) {
        request(cloudmBoxApi.getMachineBrandInfo(), view, onSuccess = { info, loadMore ->
            val position = getPosition(brandId, info)
            view.loadSuccess(info, loadMore)
            view.scrollToPosition(position)
        }, onFailure = { errorMsg ->
            view.loadFailure(errorMsg)
        })
    }

    override fun loadMachineModelInfo(typeId: Int, brandId: Int, modelId: Int) {
        request(cloudmBoxApi.getMachineModelInfo(typeId, brandId), view,
                onSuccess = { info, loadMore ->
                    val position = getPosition(modelId, info)
                    view.loadSuccess(info, loadMore)
                    view.scrollToPosition(position)
                }, onFailure = { errorMsg ->
            view.loadFailure(errorMsg)
        })
    }


    private fun getPosition(id: Int, list: ArrayList<MachineInfo>?): Int {
        if (list == null || list.size == 0) {
            return -1
        }
        val size = list.size
        for (i in 0 until size) {
            list[i].selected = false
        }
        for (i in 0 until size) {
            if (id == list[i].id) {
                list[i].selected = true
                return i
            }
        }
        return -1
    }
}